package com.koushikdutta.ion.cookie;

import com.example.ohosasynclibrary.async.http.Headers;
import com.example.ohosasynclibrary.async.http.SimpleMiddleware;
import com.example.ohosasynclibrary.async.util.LogUtil;
import com.example.ohosasynclibrary.async.util.TextUtils;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.IonLog;
import com.koushikdutta.ion.conscrypt.ConscryptMiddleware;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.util.List;
import java.util.Map;

/**
 * Created by koush on 5/29/13.
 */
public class CookieMiddleware extends SimpleMiddleware {
    CookieManager manager;
    Preferences preferences;

    public CookieStore getCookieStore() {
        return manager.getCookieStore();
    }

    public void clear() {
        maybeInit();
        getCookieStore().removeAll();
        preferences.clear().flush();
    }

    public CookieManager getCookieManager() {
        maybeInit();
        return manager;
    }

    Ion ion;

    public CookieMiddleware(Ion ion) {
        this.ion = ion;
    }

    public void reinit() {
        manager = new CookieManager(null, null);
        final DatabaseHelper databaseHelper = new DatabaseHelper(ion.getContext());
        preferences = databaseHelper.getPreferences(ion.getName() + "-cookies");

        Map<String, ?> allPrefs = preferences.getAll();
        for (String key : allPrefs.keySet()) {
            try {
                String value = preferences.getString(key, null);
                Headers headers = new Headers();
                String[] lines = value.split("\n");
                boolean first = true;
                for (String line : lines) {
                    if (first) {
                        first = false;
                    } else if (!TextUtils.isEmpty(line)) {
                        headers.addLine(line);
                    }
                }
                manager.put(URI.create(key), headers.getMultiMap());
            } catch (Exception e) {
                IonLog.e("Ion", "unable to load cookies" + e.getMessage());
            }
        }
    }

    public static void addCookies(Map<String, List<String>> allCookieHeaders, Headers headers) {
        for (Map.Entry<String, List<String>> entry : allCookieHeaders.entrySet()) {
            String key = entry.getKey();
            if ("Cookie".equalsIgnoreCase(key) || "Cookie2".equalsIgnoreCase(key)) {
                headers.addAll(key, entry.getValue());
            }
        }
    }

    private void maybeInit() {
        if (manager == null)
            reinit();
    }

    @Override
    public void onRequest(OnRequestData data) {
        maybeInit();
        try {
            Map<String, List<String>> cookies = manager.get(
                    URI.create(
                            data.request.getUri().toString()),
                    data.request.getHeaders().getMultiMap());
            addCookies(cookies, data.request.getHeaders());
        } catch (Exception e) {
            LogUtil.error(ConscryptMiddleware.class.getName(), e.getMessage());
        }
    }

    @Override
    public void onHeadersReceived(OnHeadersReceivedData data) {
        maybeInit();
        try {
            put(URI.create(data.request.getUri().toString()), data.response.headers());
        } catch (Exception e) {
            LogUtil.error(ConscryptMiddleware.class.getName(), e.getMessage());
        }
    }

    public void put(URI uri, Headers headers) {
        maybeInit();
        try {
            manager.put(uri, headers.getMultiMap());

            // no cookies to persist.
            if (headers.get("Set-Cookie") == null)
                return;

            List<HttpCookie> cookies = manager.getCookieStore().get(uri);

            Headers dump = new Headers();
            for (HttpCookie cookie : cookies) {
                dump.add("Set-Cookie", cookie.getName() + "=" + cookie.getValue() + "; path=" + cookie.getPath());
            }

            String key = uri.getScheme() + "://" + uri.getAuthority();
            preferences.putString(key, dump.toPrefixString("HTTP/1.1 200 OK")).flush();
        } catch (Exception e) {
            LogUtil.error(ConscryptMiddleware.class.getName(), e.getMessage());
        }
    }
}
